package com.itheima.service.impl;

import com.itheima.dao.DeptDao;
import com.itheima.domain.Dept;
import com.itheima.service.DeptService;
import com.itheima.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.UUID;

public class DeptServiceImpl implements DeptService {
    @Override
    public List<Dept> findAll() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        DeptDao mapper = sqlSession.getMapper(DeptDao.class);
        List<Dept> levelOne = mapper.findLevelOne();
        for (Dept dept : levelOne) {
            String deptId = dept.getDeptId();
            List<Dept> levelTwo = mapper.findLevelTwo(deptId);
            for (Dept dept1 : levelTwo) {
                String deptId1 = dept1.getDeptId();
                List<Dept> levelThree = mapper.findLevelTwo(deptId1);
                dept1.setChildren(levelThree);
            }
            dept.setChildren(levelTwo);
        }
        sqlSession.close();
        return levelOne;
    }

    @Override
    public void add(Dept dept) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        DeptDao mapper = sqlSession.getMapper(DeptDao.class);
        String id = UUID.randomUUID().toString();
        dept.setDeptId(id);
        mapper.add(dept);
        sqlSession.close();
    }

    @Override
    public void update(Dept dept) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        DeptDao mapper = sqlSession.getMapper(DeptDao.class);
        mapper.update(dept);
        sqlSession.close();
    }

    @Override
    public void delete(String deptId) {
        SqlSession sqlSession =null;
        try {
            sqlSession = MybatisUtils.getSqlSession(false);
            DeptDao mapper = sqlSession.getMapper(DeptDao.class);
            mapper.delete(deptId);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new  RuntimeException("请删除子部门!",e);
        } finally {
            sqlSession.close();
        }
    }
}
